#include "protreewidget.h"
#include <QDir>
#include "protreeitem.h"
#include "const_enum.h"
#include "protreethread.h"
#include "removeprodialog.h"
#include "slideshowdlg.h"
#include <QAudioOutput>
#include <QFileDialog>
#include <QGuiApplication>
#include <QHeaderView>
#include <QMenu>
#include <QProgressDialog>


ProTreeWidget::ProTreeWidget(QWidget *parent):QTreeWidget(parent),_musiclist({}),_currentIndex(0)
{
    header()->hide();
    connect(this, &ProTreeWidget::itemPressed, this, &ProTreeWidget::SlotItemPressed);
    _action_import = new QAction(QIcon(":/icon/import.png"),tr("导入文件"), this);
    connect(_action_import, &QAction::triggered, this, &ProTreeWidget::SlotImport);
    //双击事件
    connect(this, &ProTreeWidget::itemDoubleClicked, this, &ProTreeWidget::SlotDoubleClickItem);

    _action_setstart = new QAction(QIcon(":/icon/core.png"), tr("设置活动项目"),this);
    _action_closepro = new QAction(QIcon(":/icon/close.png"), tr("关闭项目"), this);
    connect(_action_closepro, &QAction::triggered, this, &ProTreeWidget::SlotClosePro);
    connect(_action_setstart, &QAction::triggered, this, &ProTreeWidget::SlotSetActive);

    _action_slideshow = new QAction(QIcon(":/icon/slideshow.png"), tr("轮播图播放"),this);
    connect(_action_slideshow, &QAction::triggered, this, &ProTreeWidget::SlotSlideShow);

    _player = new QMediaPlayer(this);
    _audioOutput = new QAudioOutput(this);
    _player->setAudioOutput(_audioOutput );
    _audioOutput->setVolume(0.5);
    //轮播音乐
    connect(_player, &QMediaPlayer::playbackStateChanged, this, [=]() {
        if (_player->playbackState() == QMediaPlayer::StoppedState) {
            _currentIndex = (_currentIndex + 1) % _musiclist.size();
            _player->setSource(QUrl::fromLocalFile(_musiclist[_currentIndex]));
            _player->play();
        }
    });
}

void ProTreeWidget::AddToTree(const QString &name, const QString &path)
{
    qDebug() << "ProTreeWidget::AddProToTree name is " << name << " path is " << path;
    QDir dir(path);
    QString file_path = dir.absoluteFilePath(name);
    //检测重名，判断路径和名字都一样则拒绝加入
    if(_set_path.find(file_path) != _set_path.end()){
        qDebug() << "file has loaded" ;
        return;
    }
    //构造项目用的文件夹
    QDir pro_dir(file_path);
    //如果文件夹不存在则创建
    if(!pro_dir.exists()){
        bool enable = pro_dir.mkpath(file_path);
        if(!enable){
            qDebug() << "pro_dir make path failed" ;
            return;
        }
    }
    _set_path.insert(file_path);
    auto * item = new ProTreeItem(this, name, file_path,TreeItemPro);
    item->setData(0,Qt::DisplayRole, name);
    item->setData(0,Qt::DecorationRole, QIcon(":/icon/dir.png"));
    item->setData(0,Qt::ToolTipRole, file_path);
}

void ProTreeWidget::SlotItemPressed(QTreeWidgetItem *pressedItem, int column)
{
    qDebug() << "ProTreeWidget::SlotItemPressed";
    if(QGuiApplication::mouseButtons() == Qt::RightButton)   //判断是否为右键
    {
        QMenu menu(this);
        qDebug() << "menu addr is " << &menu;
        int itemtype = (int)(pressedItem->type());
        if (itemtype == TreeItemPro)//项目根目录？
        {
            _right_btn_item = dynamic_cast<ProTreeItem *>(pressedItem);
            menu.addAction(_action_import);
            menu.addAction(_action_closepro);
            menu.addAction(_action_setstart);
            menu.addAction(_action_slideshow);
            menu.exec(QCursor::pos());//事件监听,但我觉得主要是弹出作用。
        }
    }
}

void ProTreeWidget::SlotImport()
{
    QFileDialog file_dialog;
    file_dialog.setFileMode(QFileDialog::Directory);
    file_dialog.setWindowTitle("选择导入的文件夹");
    QString path = "";
    if(!_right_btn_item){
        qDebug() << "_right_btn_item is empty";
        path = QDir::currentPath();
        return ;
    }

    path = dynamic_cast<ProTreeItem*>(_right_btn_item)->GetPath();

    file_dialog.setDirectory(path);
    file_dialog.setViewMode(QFileDialog::Detail);

    QStringList fileNames;
    if (file_dialog.exec()){
        fileNames = file_dialog.selectedFiles();
    }

    if(fileNames.length() <= 0){
        return;
    }

    QString import_path = fileNames.at(0);
    // qDebug() << "import_path is " << import_path << endl;

    int file_count = 0;
    //创建模态对话框
    _dialog_progress = new QProgressDialog(this);
    //耗时操作放在线程中操作
    _thread_create_pro = std::make_shared<ProTreeThread>(std::ref(import_path), std::ref(path),
                                                         _right_btn_item,
                                                         std::ref(file_count), this,_right_btn_item,nullptr);
    //连接更新进度框操作
    connect(_thread_create_pro.get(), &ProTreeThread::SigUpdateProgress,
            this, &ProTreeWidget::SlotUpdateProgress);
    //连接导入完成信号
    connect(_thread_create_pro.get(), &ProTreeThread::SigFinishProgress, this,
            &ProTreeWidget::SlotFinishProgress);
    connect(_dialog_progress, &QProgressDialog::canceled, this, &ProTreeWidget::SlotCancelProgress);
    //ProTreeWidget::SlotCancelProgress >> ProTreeWidget::SigCancelProgress
    connect(this, &ProTreeWidget::SigCancelProgress, _thread_create_pro.get(),&ProTreeThread::SlotCancelProgress);
    _thread_create_pro->start();
    //连接信号和槽
    _dialog_progress->setWindowTitle("Please wait...");
    _dialog_progress->setFixedWidth(PROGRESS_WIDTH);
    _dialog_progress->setRange(0, PROGRESS_MAX);
    _dialog_progress->exec();
}

void ProTreeWidget::SlotUpdateProgress(int count)
{
    qDebug() << "count is " << count;
    if(!_dialog_progress){
        qDebug() << "dialog_progress is empty!!!";
        return;
    }
    if(count >= PROGRESS_MAX){
        _dialog_progress->setValue(count%PROGRESS_MAX);
    }else{
        _dialog_progress->setValue(count%PROGRESS_MAX);
    }
}
void ProTreeWidget::SlotCancelProgress()
{
    //  _thread_create_pro->terminate();
    emit SigCancelProgress();
    delete _dialog_progress;
    _dialog_progress =nullptr;
}
void ProTreeWidget::SlotFinishProgress()
{
    _dialog_progress->setValue(PROGRESS_MAX);
    _dialog_progress->deleteLater();//事件处理完毕后再删除.
}

void ProTreeWidget::SlotDoubleClickItem(QTreeWidgetItem *item, int column)
{
    qDebug() << "ProTreeWidget::SlotDoubleClickItem" ;
    if(QGuiApplication::mouseButtons() == Qt::LeftButton)   //判断是否为左键
    {
        auto * tree_doubleItem = dynamic_cast<ProTreeItem*>(item);
        if(!tree_doubleItem){
            return;
        }
        int itemtype = (int)(tree_doubleItem->type());
        if(itemtype == TreeItemPic){//必须是图片
            emit SigUpdateSelected(tree_doubleItem->GetPath());
            _selected_item = tree_doubleItem;
        }
    }
}

void ProTreeWidget::SlotPreShow(){
    if(!_selected_item){
        return;
    }
    auto * curItem = dynamic_cast<ProTreeItem*>(_selected_item)->GetPreItem();
    if(!curItem){
        return;
    }
    emit SigUpdatePic(curItem->GetPath());
    _selected_item = curItem;
    this->setCurrentItem(curItem);
}
void ProTreeWidget::SlotNextShow(){
    if(!_selected_item){
        return;
    }
    auto * curItem = dynamic_cast<ProTreeItem*>(_selected_item)->GetNextItem();
    if(!curItem){
        return;
    }
    emit SigUpdatePic(curItem->GetPath());
    _selected_item = curItem;
    this->setCurrentItem(curItem);
}

void ProTreeWidget::SlotOpenPro(QString path)
{
    if (_set_path.find(path) != _set_path.end()) {
        qDebug() << "file has loaded";
        return;
    }

    _set_path.insert(path);
    int file_count = 0;
    QDir pro_dir(path);
    const QString& proname = pro_dir.dirName();

    _thread_open_pro = std::make_shared<OpenTreeThread>(path, file_count, this, nullptr);
    _thread_open_pro->start();

    _open_progressdlg = new QProgressDialog(this);

    //连接更新进度框操作
    connect(_thread_open_pro.get(), &OpenTreeThread::SigUpdateProgress,
        this, &ProTreeWidget::SlotUpOpenProgress);

    connect(_thread_open_pro.get(), &OpenTreeThread::SigFinishProgress, this,
        &ProTreeWidget::SlotFinishOpenProgress);

    _open_progressdlg->setWindowTitle("Please wait...");
    _open_progressdlg->setFixedWidth(PROGRESS_WIDTH);
    _open_progressdlg->setRange(0, PROGRESS_MAX);
    _open_progressdlg->exec();
}

void ProTreeWidget::SlotSetMusic()
{
    qDebug() << "ProTreeWidget::SlotSetMusic" ;
    QFileDialog file_dialog;
    file_dialog.setFileMode(QFileDialog::ExistingFiles);
    file_dialog.setWindowTitle("选择导入的文件夹");
    file_dialog.setDirectory(QDir::currentPath());
    file_dialog.setViewMode(QFileDialog::Detail);
    file_dialog.setNameFilter("(*.mp3)");
    QStringList fileNames;
    if (file_dialog.exec()){
        fileNames = file_dialog.selectedFiles();
    }
    if(fileNames.length() <= 0){
        return;
    }
    _musiclist.clear();
    _musiclist = fileNames;
    qDebug()<<"_musiclist.size(): "<<_musiclist.size();
}

void ProTreeWidget::SlotStartMusic()
{
    qDebug()<< "ProTreeWidget::SlotStartMusic";
    if(_musiclist.empty())return;
    _player->setSource(QUrl::fromLocalFile(_musiclist[_currentIndex]));
    _player->play();
}

void ProTreeWidget::SlotStopMusic()
{
    qDebug()<< "ProTreeWidget::SlotStopMusic";

    _player->pause();
}

void ProTreeWidget::SlotFinishOpenProgress()
{
    if (!_open_progressdlg) {
        return;
    }
    _open_progressdlg->setValue(PROGRESS_MAX);
    delete  _open_progressdlg;
    _open_progressdlg = nullptr;
}

void ProTreeWidget::SlotUpOpenProgress(int count)
{
    if (!_open_progressdlg) {
        return;
    }
    //qDebug()<<"SlotUpOpenProgress count is " << count;
    if (count >= PROGRESS_MAX) {
        _open_progressdlg->setValue(count % PROGRESS_MAX);
    }
    else {
        _open_progressdlg->setValue(count % PROGRESS_MAX);
    }
}

void ProTreeWidget::SlotClosePro()
{
    RemoveProDialog  remove_pro_dialog;
    auto res = remove_pro_dialog.exec();
    bool b_remove = remove_pro_dialog.IsRemoved();
    auto index_right_btn = this->indexOfTopLevelItem(_right_btn_item);
    auto * protreeitem = dynamic_cast<ProTreeItem*>(_right_btn_item);
    auto * selecteditem = dynamic_cast<ProTreeItem*>(_selected_item);
    auto delete_path = protreeitem->GetPath();
    qDebug() << "remove project from path: " << delete_path;
    _set_path.remove(delete_path);
    if(b_remove){
        QDir delete_dir(delete_path);
        delete_dir.removeRecursively();
    }
    if(protreeitem == _active_item){
        _active_item = nullptr;
    }
    //如果当前显示的图片在这个项目中的话。
    if(selecteditem && protreeitem == selecteditem->GetRoot()){
        selecteditem = nullptr;
        emit SigClearSelected();
    }
    delete this->takeTopLevelItem(index_right_btn);
    _right_btn_item = nullptr;
}

void ProTreeWidget::SlotSetActive()
{
    if(!_right_btn_item){
        return;
    }
    QFont nullFont;
    nullFont.setBold(false);
    _active_item = _right_btn_item;
    nullFont.setBold(true);
    _active_item->setFont(0,nullFont);
}

void ProTreeWidget::SlotSlideShow()
{
    if(!_right_btn_item){
        return;
    }
    auto *right_pro_item = dynamic_cast<ProTreeItem*>(_right_btn_item);
    auto * last_child_item = right_pro_item->GetLastPicChild();
    if(!last_child_item){
        return;
    }
    qDebug()<< "last child item name is " << last_child_item->GetPath();
    auto * first_child_item = right_pro_item->GetFirstPicChild();
    if(!first_child_item){
        return;
    }
    qDebug()<< "first child item name is " << first_child_item->GetPath();
    _slide_show_dlg = std::make_shared<SlideShowDlg>(first_child_item, last_child_item,this);
    _slide_show_dlg->setModal(true);
    _slide_show_dlg->showMaximized();
}
